//
//  ImageGalleryViewController.swift
//  DKE-Album
//
//  Created by dagny on 2025/9/29.
//  Copyright © 2025 杨东宝. All rights reserved.
//

import Foundation
import UIKit


protocol ImageGalleryViewControllerDelegate: AnyObject {
    func imageGalleryViewController(_ controller: ImageGalleryViewController, didFinishCroppingImages images: [UIImage])
}
class ImageGalleryViewController: YDBBaseViewController {
    
    // MARK: - Properties
    weak var delegate: ImageGalleryViewControllerDelegate?
    var selectScreen:Screen?
    private var images: [UIImage] = []
    private var currentPage = 0
    
    lazy var tipLabel: UILabel = {
        let label = UILabel()
        label.textColor = HexRGB(0x3d4466)
        label.font = DIMENSION_FONT_OF_SIZE(18)
        label.text = "changePhoto".localized
        return label
    }()
    //MARK: - 按钮
    lazy var confirmBtn: UIButton = {
        let btn =  UIButton.init(type: .custom)
        btn.setTitle("confirm".localized, for: .normal)
        btn.setTitleColor(.white, for: .normal)
        btn.titleLabel?.font = DIMENSION_FONT_OF_SIZE(14)
        btn.backgroundColor = HexRGB(0x3D4466)
        btn.layer.cornerRadius = DIMENSION_VALUE(20)
        btn.layer.masksToBounds = true
        btn.addTarget(self, action: #selector(confirmBtnClick(_ : )), for: .touchUpInside)
        return btn
    }()
    
    // MARK: - UI Components
    private lazy var collectionView: UICollectionView = {
        let layout = UICollectionViewFlowLayout()
        layout.scrollDirection = .horizontal
        layout.minimumLineSpacing = 0
        layout.minimumInteritemSpacing = 0
        
        let collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout)
        collectionView.isPagingEnabled = true
        collectionView.showsHorizontalScrollIndicator = false
        collectionView.register(ImageCell.self, forCellWithReuseIdentifier: "ImageCell")
        collectionView.dataSource = self
        collectionView.delegate = self
        collectionView.backgroundColor = .white
        collectionView.layer.cornerRadius = 10
        collectionView.layer.masksToBounds = true
        collectionView.translatesAutoresizingMaskIntoConstraints = false
        return collectionView
    }()
    
    private lazy var pageControl: UIPageControl = {
        let pageControl = UIPageControl()
        pageControl.currentPageIndicatorTintColor = HexRGB(0x3d4466)
        pageControl.pageIndicatorTintColor = .gray
        pageControl.translatesAutoresizingMaskIntoConstraints = false
        return pageControl
    }()
    
    // MARK: - Initialization
    init(images: [UIImage],screen:Screen) {
        self.images = images
        self.selectScreen = screen
        super.init()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // MARK: - Lifecycle
    override func viewDidLoad() {
        super.viewDidLoad()
        self.navigationItem.title = "croping".localized
        setupUI()
        setupConstraints()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        updatePageControl()
    }
    
    // MARK: - Setup
    private func setupUI() {
        view.addSubview(tipLabel)
        view.addSubview(confirmBtn)
        view.addSubview(collectionView)
        view.addSubview(pageControl)
        pageControl.numberOfPages = images.count
        pageControl.currentPage = 0
    }
    
    private func setupConstraints() {
        
        tipLabel.snp.makeConstraints { make in
            make.centerX.equalTo(view.snp_centerX)
            make.top.equalToSuperview().offset(20)
        }
        confirmBtn.snp.makeConstraints { make in
            make.left.equalTo(view.snp_left).offset(DIMENSION_VALUE(20))
            make.right.equalTo(view.snp_right).offset(DIMENSION_VALUE(-20))
            make.height.equalTo(DIMENSION_VALUE(40))
            make.bottom.equalToSuperview().offset(-DIMENSION_VALUE(20))
        }
        pageControl.snp.makeConstraints { make in
            make.centerX.equalTo(view.snp_centerX)
            make.bottom.equalTo(confirmBtn.snp_top).offset(-DIMENSION_VALUE(20))
        }
        collectionView.snp.makeConstraints { make in
            make.left.equalTo(view.snp_left).offset(10)
            make.right.equalTo(view.snp_right).offset(-10)
            make.top.equalTo(tipLabel.snp_bottom).offset(40)
            make.bottom.equalTo(pageControl.snp_top).offset(DIMENSION_VALUE(-20))
        }
    }

    private func updatePageControl() {
        pageControl.currentPage = currentPage
    }
    //MARK: - 确定按钮
   @objc func confirmBtnClick(_ btn :UIButton) {
       self.delegate?.imageGalleryViewController(self, didFinishCroppingImages: images)
       self.navigationController?.popViewController(animated: true)
   }
}

// MARK: - UICollectionView DataSource & Delegate
extension ImageGalleryViewController: UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return images.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ImageCell", for: indexPath) as! ImageCell
        cell.configure(with: images[indexPath.item])
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return collectionView.bounds.size
    }
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        let pageIndex = round(scrollView.contentOffset.x / scrollView.frame.width)
        currentPage = Int(pageIndex)
        updatePageControl()
    }
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let image = images[indexPath.row]
        // 创建裁剪控制器
        let cropViewController = ImageCropViewController(image: image, cropRatio: CGSize(width: selectScreen!.width, height: selectScreen!.height))
             cropViewController.delegate = self
                cropViewController.modalPresentationStyle = .fullScreen
            self.navigationController?.pushViewController(cropViewController, animated: true)
    }
}
extension ImageGalleryViewController:ImageCropViewControllerDelegate{
    func imageCropViewController(_ controller: ImageCropViewController, didFinishCroppingImage image: UIImage) {
        images[currentPage] = image
        self.collectionView.reloadData()
    }
}

// MARK: - Image Cell
class ImageCell: UICollectionViewCell {
    
    private let imageView: UIImageView = {
        let imageView = UIImageView()
        imageView.contentMode = .scaleAspectFit
        imageView.clipsToBounds = true
        imageView.translatesAutoresizingMaskIntoConstraints = false
        return imageView
    }()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    private func setupUI() {
        contentView.addSubview(imageView)
        
        NSLayoutConstraint.activate([
            imageView.topAnchor.constraint(equalTo: contentView.topAnchor),
            imageView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor),
            imageView.trailingAnchor.constraint(equalTo: contentView.trailingAnchor),
            imageView.bottomAnchor.constraint(equalTo: contentView.bottomAnchor)
        ])
    }
    func configure(with image: UIImage) {
        imageView.image = image
    }
 
}
